import {messages} from "share/common";
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { Button } from 'antd';
import 'styles/expense/expense-adjunct-item.scss';
import FileViewer from 'components/file-viewer';
import wordImage from 'images/file-type/word.png';
import pptImage from 'images/file-type/ppt.png';
import excelImage from 'images/file-type/excel.png';
import txtImage from 'images/file-type/txt.png';
import pdfImage from 'images/file-type/pdf.png';
import unknownImage from 'images/file-type/unknown.png';
import doubt from 'images/expense-detail/doubt.png'
import { RightArrow } from '../svg-component/index';
import wrapAttachmentHeader from '../component/attachment-header-hoc';
import defaultExpenseTypeIcon from 'images/expense/default-expense-type.png';
import { InvoiceLabels, InvoiceCell, InvoiceOrigin } from '../component/func-component';

@wrapAttachmentHeader
@connect(mapStateToProps)
class ExpenseAdjunctItem extends Component {

  static contextTypes = {
    currentExpense: React.PropTypes.object,
    isWaitForAudit: React.PropTypes.bool
  };

  state = {
    result: [],
    previewVisible: false,
    previewIndex: 0
  };

  // 预览
  handlePreview = () => {
    const { currentAdjunct } = this.props;
    if (this.isAllowedFile(currentAdjunct.fileName)) {
      this.setState({
        result: [{
          fileName: currentAdjunct.fileName,
          url: currentAdjunct.fileURL
        }]
      }, () => this.setState({ previewVisible: true }));
    } else {
      window.open(currentAdjunct.fileURL, '_blank');
    }
  };

  getExtension = fileName => {
    let sections = fileName.split('.');
    let extension = sections[sections.length - 1].toLowerCase();
    return extension.length > 3 ? extension.substring(0, 4) : extension;
  };

  isAllowedFile = (fileName) => {
    let extension = this.getExtension(fileName);
    let imageExtension = ['png', 'gif', 'jpg', 'jpeg', 'bmp', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt', 'pdf'];
    return imageExtension.has(extension);
  };

  isImage = () => {
    const {  currentAdjunct: {fileName } } = this.props;
    if (!fileName) {
      return false;
    }
    let extension = this.getExtension(fileName);
    let imageExtension = ['png', 'gif', 'jpg', 'jpeg', 'bmp'];
    return imageExtension.has(extension);
  };

  handleUrl = () => {
    const {currentAdjunct: { fileURL, fileName } } = this.props;
    let extension = this.getExtension(fileName);
    let imageExtension = ['png', 'gif', 'jpg', 'jpeg', 'bmp'];
    let wordExtension = ['doc', 'docx'];
    let pptExtension = ['ppt', 'pptx'];
    let excelExtension = ['xls', 'xlsx'];
    let txtExtension = ['txt'];
    let pdfExtension = ['pdf'];
    if (imageExtension.has(extension)) {
      return fileURL;
    }
    if (wordExtension.has(extension)) {
      return wordImage;
    }
    if (pptExtension.has(extension)) {
      return pptImage;
    }
    if (excelExtension.has(extension)) {
      return excelImage;
    }
    if (txtExtension.has(extension)) {
      return txtImage;
    }
    if (pdfExtension.has(extension)) {
      return pdfImage;
    }
    return unknownImage;
  };

  render() {
    const { title, bodyWords, origin, labels = [], flag, descAmount, totalAmount, currentAdjunct: { pdfDamaged, singleReimbursed },
      receiptChanges = {}, receiptLabelsDesc, currentAdjunct, className, isDetail, isEdit, isDelete, isPrint, invoicedReceiptAmount, isShowUnUsedAmount, isShowBodyWords, entry } = this.props;
    const currentExpense = this.context.currentExpense || this.props.currentExpense || {};
    const invoiceOID = currentExpense.invoiceOID;
    const { previewVisible, previewIndex, result } = this.state;
    return (
      <section className={`adjunct-item ${className}`}>
        <div
          className={`adjunct-item-header ${flag === 'attachment' && 'adjunct-item-header-attachment'} ${isShowBodyWords && 'adjunct-item-line'}`}>
          <div className="adjunct-item-header-content">
            <div className="adjunct-item-header-title">
              <div>
                {title.render && title.render('', currentAdjunct, receiptChanges.type)}
              </div>
              {origin.render && <InvoiceOrigin language={this.props.language} origin={origin.render('', currentAdjunct)}/>}
            </div>
            {
              totalAmount.render &&
              <div className="adjunct-item-all-amounts">
                {totalAmount.render && totalAmount.render('', currentAdjunct, invoiceOID)}

                {invoicedReceiptAmount.render && !['finance-invoice-list', 'invoice-management-platform'].includes(entry) &&
                <span
                  onClick={() => {isDelete && this.props.editUsedAmount()}}
                  className="adjunct-item-used-amount"
                >
                  {invoicedReceiptAmount.name}：
                  {invoicedReceiptAmount.render(currentAdjunct[isShowUnUsedAmount ? 'unUsedAmount' : 'invoicedReceiptAmount'], currentAdjunct)}
                  {
                    isDelete && <RightArrow/>
                  }
                  {
                    !singleReimbursed &&
                    <img
                      className="adjunct-item-used-amount-icon"
                      src={doubt}
                      onClick={(e) => {e.stopPropagation();this.props.showUsedMsg();}}
                      alt={'doubt.png'}
                    />
                  }
                </span>
                }

              </div>
            }
            {
              descAmount.render &&
              <div className="adjunct-item-desc-amounts">
                {descAmount.render && descAmount.render('', currentAdjunct, receiptChanges)}
              </div>
            }

            {flag === 'attachment' &&
            <div className="adjunct-item-attachment">
              <img
                src={this.handleUrl()}
                onError={e => e.target.src = defaultExpenseTypeIcon}
                className={`adjunct-item-image ${!this.isImage() && 'adjunct-item-no-image'}`}
                onClick={this.handlePreview}
              />
            </div>
            }

            <div className="adjunct-item-operation">
              {labels && labels[0] ?
                <InvoiceLabels
                  labels={labels.filter(item => item.type !== 'HAND_RECODE_RECEIPT')}
                  pdfDamaged={pdfDamaged}
                  receiptChanges={receiptChanges}
                  receiptLabelsDesc={receiptLabelsDesc[currentAdjunct.id]}
                />
                : <div/>
              }
              <div className="adjunct-item-right">
                {!isDetail && <div className="adjunct-item-right-button">
                  <a onClick={this.props.handleShowMore}
                     type="link">{messages('common.view')/*查看*/}</a>
                </div>}
                {
                  isEdit && <Button size={'small'} className="adjunct-item-right-button" type={'primary'} onClick={this.props.handleEdit}>{messages('common.edit')/*编辑*/}</Button>
                }
                {
                  isPrint && <Button size={'small'} className="adjunct-item-right-button" type={'primary'} onClick={this.props.handlePrint}>{messages('common.print')/*打印*/}</Button>
                }
                {
                  isDelete && <Button size={'small'}  className="adjunct-item-right-button" type={'danger'} onClick={this.props.handleDelete}>{messages('common.delete')/*删除*/}</Button>
                }
              </div>
            </div>
          </div>
        </div>
        {
          isShowBodyWords && bodyWords && bodyWords[0] &&
          <div className="adjunct-item-body">
            <InvoiceCell
              bodyWords={bodyWords}
              receiptChanges={receiptChanges}
              currentAdjunct={currentAdjunct}
            />
          </div>
        }
        <FileViewer
          visible={previewVisible}
          attachments={result}
          defaultIndex={previewIndex}
          onCancel={() => this.setState({ previewVisible: false })}
          urlKey="url"
          valueKey="url"
        />
      </section>
    );
  }

  static PropTypes = {
    receiptLabelsDesc: PropTypes.object,
    receiptChanges: PropTypes.object,
    isShowBodyWords: PropTypes.bool
  };

  static defaultProps = {
    receiptLabelsDesc: {},
    receiptChanges: {},
    isShowBodyWords: true
  };

}

ExpenseAdjunctItem.propTypes = {
  headerWords: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
  };
}

export default ExpenseAdjunctItem;

